package com.corejsf;

import java.io.Serializable;
import javax.enterprise.context.SessionScoped;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
import javax.faces.validator.ValidatorException;
import javax.inject.Inject;
import javax.inject.Named;

@Named
@SessionScoped
public class UserBean implements Serializable {
	private User currentUser  = new User("Intast navn", "Indtast password"); 
	private String navn, pass, passRepeat;
	@Inject
	Service service;

	public void setCurrentUser(User user) {
		currentUser = user;
	}
	
	public void createUser(FacesContext context, UIComponent component,Object value){
		
		
  	  UIInput passInput = (UIInput) component.findComponent("pass");
  	  UIInput navnInput = ((UIInput) component.findComponent("navn"));
  	  
  	  String name = ((String) navnInput.getLocalValue().toString());
  	  String p1 = ((String) passInput.getLocalValue().toString());  
  	  String p2 = ((String) value).toString();
  	  
		if (!isValid(p1, p2)) {
	          FacesMessage message = com.corejsf.util.Messages.getMessage("com.corejsf.messages", "Du indtastede ikke det samme kodeord begge gange", null);
	          message.setSeverity(FacesMessage.SEVERITY_ERROR);
	          throw new ValidatorException(message);
	       }
	      else{
	    	  service.createUser(name, p1);
	      }
	}
	
	public boolean isValid(String p1, String p2){
		if (!p1.equals(p2))
			return false;
		else return true;
	}

	public String getNavn() {
		return navn;
	}

	public void setNavn(String navn) {
		this.navn = navn;
	}

	public String getPass() {
		return pass;
	}

	public void setPass(String pass) {
		this.pass = pass;
	}

	public String getPassRepeat() {
		return passRepeat;
	}

	public void setPassRepeat(String passRepeat) {
		this.passRepeat = passRepeat;
	}

	public User getCurrentUser() {
		return currentUser;
	}

	public String login() {
		if (service.isUser(currentUser.getUserName(), currentUser.getPassword()) && service.getUser()!=null)
			return "categoriList";
		return "error";
	}
}
